<?php

use Illuminate\Support\Facades\DB;
require_once('yasuo.php');

    /**
     * summary
     */
    class Moban
    {


    /**
     * 发送模板消息
     */
    public function send($openid,$template_id,$page,$form_id,$data)
    {
        $access_token = $this->getAccessToken();
        $postData = [
                'touser'  => $openid,  //用户openid
                'template_id' => $template_id, //模板id
                'page' => $page,  //跳转页面
                'form_id' => $form_id, // 用户订单预支付id
                'data' => $data, //提交的数据
        ];
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token ;
        $result = http_post($url,$postData,'json');
        return json_decode($result);
    }

    /**
     * 获取小程序码
     */
    public function wxcode($redid,$password,$wxurl,$type){
        $access_token = $this->getAccessToken();
        $page =  "pages/voice_box/{$type}/index";
        $width = 300;
        $auto_color = false;
        $line_color =  '{"r":"0","g":"0","b":"0"}' ;
        $postData = [
            'scene' => $redid,
            'page' => $page,
            'width' => $width,
            // 'auto_color' => $auto_color,
            // 'line_color' => $line_color
        ];
        // $postData = json_encode($postData);
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
        $result = http_post($url,$postData,'json');
        // $sData = file_get_contents("php://input");
        $Path = "/public/wxcode/";
        $fileName = base_path() . $Path;//文件路径
        if (!file_exists($fileName)) {
            //进行文件创建
            mkdir($fileName, 0777, true);
        }
        $imageSavePath = $fileName . $redid.'.png';
        file_put_contents($imageSavePath,$result);
        // return $result;
        $this->test($imageSavePath);
        $this->codeimg($imageSavePath,$password);
        $this->wximg($wxurl,$redid);
        // $reurl = './wxcode/wx' . $redid . '.png';
        // $percent = 0.8;
        // (new \imgcompress($reurl,$percent))->compressImg($reurl);
     }


     /**
     * 头像合成
     */

    public function wximg($outfile,$redid){
        //添加海报背景图
                  $dst_path = "./wxcode/{$redid}.png";  //海报背景图路径
                  $src_path = $outfile; //二维码路径
                  imagepress($src_path,$percent='0.17');//头像缩放
                  //创建图片的实例
                  $dst = imagecreatefromstring(file_get_contents($dst_path));
                  $src = imagecreatefromstring(file_get_contents($src_path));


                  //获取水印图片的宽高
                  list($src_w, $src_h) = getimagesize($src_path);

                  // 将水印图片复制到目标图片上，最后个参数50是设置透明度，这里实现半透明效果
                  imagecopymerge($dst, $src, 321, 18, 0, 0, $src_w, $src_h, 100);
                  // 如果水印图片本身带透明色，则使用imagecopy方法
                  // imagecopy($dst, $src, 207, 30, 0, 0, $src_w, $src_h);
                  //输出图片
                  list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
                  switch ($dst_type) {
                      case 1://GIF
                          // header('Content-Type: image/gif');
                          imagegif($dst,$src_path);
                          break;
                      case 2://JPG
                          // header('Content-Type: image/jpeg');
                          imagejpeg($dst,$src_path);
                          break;
                      case 3://PNG
                          // header('Content-Type: image/png');
                          imagepng($dst,$src_path);
                          break;
                      default:
                          break;
                  }
                  imagedestroy($dst);
                  imagedestroy($src);
    }


     /**
     * 背景合成
     */

     public function codeimg($outfile,$password){

           //添加海报背景图
                  $dst_path = './wxcode/beijing.png';  //海报背景图路径
                  $src_path = $outfile; //二维码路径
                  // imagepress($src_path,$percent='0.3','png');//头像缩放
                  //创建图片的实例
                  $dst = imagecreatefromstring(file_get_contents($dst_path));
                  $src = imagecreatefromstring(file_get_contents($src_path));

                  //获取水印图片的宽高
                  list($src_w, $src_h) = getimagesize($src_path);

                  //将水印图片复制到目标图片上，最后个参数50是设置透明度，这里实现半透明效果
                  // imagecopymerge($dst, $src, 220, 180, 0, 0, $src_w, $src_h, 100);
                  // 如果水印图片本身带透明色，则使用imagecopy方法
                  imagecopy($dst, $src, 281, 328, 0, 0, $src_w, $src_h);
                  //输出图片
                  list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
                  switch ($dst_type) {
                      case 1://GIF
                          // header('Content-Type: image/gif');
                          imagegif($dst,$src_path);
                          break;
                      case 2://JPG
                          // header('Content-Type: image/jpeg');
                          imagejpeg($dst,$src_path);
                          break;
                      case 3://PNG
                          // header('Content-Type: image/png');
                          imagepng($dst,$src_path);
                          break;
                      default:
                          break;
                  }
                  imagedestroy($dst);
                  imagedestroy($src);
                  $len = mb_strlen($password,'utf-8');
                  if ($len>13) {
                      $word1 = mb_substr($password, 0,12,'utf-8');
                      $word2 = mb_substr($password,12,$len-12,'utf-8');
                      $this->word($outfile,$word1,232);
                      $this->word($outfile,$word2,285);
                  }else {
                    $this->word($outfile,$password);
                  }
     }

      /**
     * 合成字体
     */
    public function word($outfile,$password,$word_h=265){
         //添加文字水印
                    $dst_path = $outfile;
                    //创建图片的实例
                    $dst = imagecreatefromstring(file_get_contents($dst_path));
                   $a=mb_convert_encoding($password,"html-entities","utf-8");
                    //打上文字
                    $font = './css/font/cc.ttf';//字体路径

                    //测试
                     $dx=imagesx($dst); //图片宽度;
                     $ix=imagettfbbox ( 38, 0 , $font , $a );      //文字宽度
                      $w = abs($ix[2] - $ix[0]);

                    $black = imagecolorallocate($dst, 255, 235, 187);//字体颜色
                     // $text = iconv("GB2312", "UTF-8", $password);
                    // imagefttext($dst, 22, 0, 174, 103, $black, $font, $cname);
                    imagefttext($dst, 38, 0, ($dx-$w)/2, $word_h, $black, $font, $a);
                    //保存图片
                    list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
                    switch ($dst_type) {
                        case 1://GIF
                            // header('Content-Type: image/gif');
                            imagegif($dst,$dst_path);
                            break;
                        case 2://JPG
                            // header('Content-Type: image/jpeg');
                            imagejpeg($dst,$dst_path);
                            break;
                        case 3://PNG
                            // header('Content-Type: image/png');
                            imagepng($dst,$dst_path);
                            break;
                        default:
                            break;
                    }
                    imagedestroy($dst);
    }

    /**
     * 生成圆角
     */

      public function test($url){
        imagepress($url,$percent='0.62');//头像缩放
        // $w = 300;  $h= 300; // original size
        list($w, $h) = getimagesize($url);
        $original_path= $url;
        $dest_path = $url;
        $src = imagecreatefromstring(file_get_contents($original_path));
        $newpic = imagecreatetruecolor($w,$h);
        imagealphablending($newpic,false);
        $transparent = imagecolorallocatealpha($newpic, 0, 0, 0, 127);
        $r=$w/2;
        for($x=0;$x<$w;$x++)
            for($y=0;$y<$h;$y++){
                $c = imagecolorat($src,$x,$y);
                $_x = $x - $w/2;
                $_y = $y - $h/2;
                if((($_x*$_x) + ($_y*$_y)) < ($r*$r)){
                    imagesetpixel($newpic,$x,$y,$c);
                }else{
                    imagesetpixel($newpic,$x,$y,$transparent);
                }
            }
        imagesavealpha($newpic, true);
        // header('Content-Type: image/png');
        imagepng($newpic, $dest_path);
        imagedestroy($newpic);
        imagedestroy($src);
        return $dest_path;
    }


    /**

     *   获取微信accessToken

     */

    public function getAccessToken(){

            $access_tokenModel = DB::table("access_token");

            $accessInfo = $access_tokenModel->where('type','=','access_token')->first();

            if ( empty($accessInfo) ) {

                $access_token = getAccessToken();

                $accessData = array(

                    'access_token' => $access_token,

                    'add_time' => time(),

                    'type' => 'access_token'

                );

                $access_tokenModel->insert($accessData);

            }elseif ( $accessInfo->add_time + 3600 < time() ){

                $access_token = getAccessToken();

                $accessData = array(

                    'access_token' => $access_token,

                    'add_time' => time()

                );

                $access_tokenModel->where('type','=','access_token')->update($accessData);

            }else{

                $access_token = $accessInfo->access_token;

            }

            return $access_token;

        }

    }




